package com.yl.immodule.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.camera.base.util.YLIMConfig;
import com.camera.base.v.BaseFragment;
import com.camera.routemodule.RouterPath;
import com.yl.immodule.R;
import com.yl.immodule.adapter.ContactsAdapter;
import com.yl.immodule.databinding.HomeFragmentContactsBinding;
import com.yl.immodule.fragment.model.ContactsViewModel;
import com.yl.immodule.util.MeetManger;
import com.yl.immodule.v.AvActivity;
import com.yl.immodule.v.ChatMessageActivity;
import com.yl.immodule.widget.ContactActionsPopup;
import com.yl.immodule.widget.InterceptViewPager;
import com.android.yl.ylicpsdk.ICPRtcEventHandler;
import com.android.yl.ylicpsdk.ICPRtcManager;
import com.hm.poc.common.TempChannel;
import com.unionbroad.greendao.MessageDialogue;
import com.unionbroad.greendao.User;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Route(path = RouterPath.path.contacts_fragment)
public class ContactsFragment extends BaseFragment<HomeFragmentContactsBinding> implements ContactsAdapter.ContactClickListener, ContactActionsPopup.ActionListener, ContactActionsPopup.PopupStateListener {
    private final static String TAG = ContactsFragment.class.getSimpleName();

    private ContactsViewModel viewModel;
    private ContactsAdapter adapter; // 改回使用原始的ContactsAdapter
    private ContactActionsPopup actionsPopup;
    private InterceptViewPager homeViewPager;
    private final Handler mainHandler = new Handler(Looper.getMainLooper());
    private int originalPaddingBottom = 0; // 保存RecyclerView原始的底部padding

    public ContactsFragment() {
    }

    public static ContactsFragment newInstance() {
        return new ContactsFragment();
    }

    public void bindViewPager(InterceptViewPager viewPager) {
        homeViewPager = viewPager;
    }
    
    @Override
    public void loadData(boolean isRefresh) {
        if (viewModel != null) {
            viewModel.loadUsers();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.home_fragment_contacts;
    }

    @Override
    public void initView() {
        try {
            // 初始化 ViewModel
            viewModel = new ViewModelProvider(this).get(ContactsViewModel.class);
            getMBinding().setViewModel(viewModel);
            getMBinding().setLifecycleOwner(getViewLifecycleOwner());
            // 设置RecyclerView
            LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
            getMBinding().recyclerView.setLayoutManager(layoutManager);
            getMBinding().recyclerView.setItemAnimator(new DefaultItemAnimator());

            // 保存原始的底部padding
            originalPaddingBottom = getMBinding().recyclerView.getPaddingBottom();
            
            adapter = new ContactsAdapter(this);
            getMBinding().recyclerView.setAdapter(adapter);
            
            // 初始化下拉刷新
            getMBinding().swipeRefresh.setOnRefreshListener(() -> {
                viewModel.loadUsers();
            });
            
            // 初始化联系人操作弹出窗口
            actionsPopup = new ContactActionsPopup(requireContext(), this);
            actionsPopup.setPopupStateListener(this);
            
            // 观察数据变化
            viewModel.userList.observe(getViewLifecycleOwner(), users -> {
                if (users != null && !users.isEmpty()) {
                    // 使用主线程更新UI，并创建新实例确保DiffUtil检测到变化
                    mainHandler.post(() -> {
                        List<User> newList = new ArrayList<>(users); // 创建新的列表实例
                        adapter.submitList(newList);  // 提交新列表到adapter
                        getMBinding().tvEmptyState.setVisibility(View.GONE);
                    });
                } else {
                    mainHandler.post(() -> {
                        adapter.submitList(new ArrayList<>());
                        getMBinding().tvEmptyState.setVisibility(View.VISIBLE);
                    });
                }
                
                // 完成数据加载后停止刷新
                if (getMBinding().swipeRefresh.isRefreshing()) {
                    getMBinding().swipeRefresh.setRefreshing(false);
                }
            });
            
            // 延迟加载真实数据，等待视图完全初始化
            mainHandler.postDelayed(() -> {
                viewModel.loadUsers();
            }, 1000);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void onResume() {
        super.onResume();
        // 尝试刷新适配器
        if (adapter != null && adapter.getItemCount() > 0) {
            adapter.notifyDataSetChanged();
        } else {
            loadData(true);
        }
    }
    
    @Override
    public void onContactClick(User user) {
        if (ICPRtcManager.getsInstance().getCurrentUser().getNumber() == user.getNumber()){
            return;
        }
        // 切换选中状态
        adapter.toggleSelection(user);
        
        // 如果有选中的联系人，显示底部弹出窗
        Set<User> selectedUsers = adapter.getSelectedUsers();
        if (!selectedUsers.isEmpty()) {
            showContactActionsPopup();
        } else {
            // 如果没有选中联系人，关闭弹窗
            if (actionsPopup != null && actionsPopup.isShowing()) {
                actionsPopup.dismiss();
            }
        }
    }
    
    @Override
    public void onAudioCallClicked() {
        Set<User> users = adapter.getSelectedUsers();
        if (users == null || users.isEmpty()) {
            return;
        }
        
        List<User> userList = new ArrayList<>(users);
        if (userList.size() == 1) {
            // 单人音频通话
            if (YLIMConfig.windowManagerChoose) {
//                MeetManger.getInstance().startMeet(
//                        requireContext().getApplicationContext(),
//                        0,
//                        userList.get(0).getNumber() + "",
//                        null,
//                        ICPRtcEventHandler.SessionType.TYPE_AUDIO_CALL,
//                        null,
//                        false);
                ARouter.getInstance()
                        .build(RouterPath.path.av_pop_activity)
                        .withString("callerId", userList.get(0).getNumber() + "")
                        .withInt("type", ICPRtcEventHandler.SessionType.TYPE_AUDIO_CALL)
                        .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                        .navigation();
            } else {
//                Intent intent = new Intent(requireContext().getApplicationContext(), AvActivity.class);
//                intent.putExtra("callerId", userList.get(0).getNumber() + "");
//                intent.putExtra("type", ICPRtcEventHandler.SessionType.TYPE_AUDIO_CALL);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                requireContext().getApplicationContext().startActivity(intent);
                ARouter.getInstance()
                        .build(RouterPath.path.av_activity)
                        .withString("callerId", userList.get(0).getNumber() + "")
                        .withInt("type", ICPRtcEventHandler.SessionType.TYPE_AUDIO_CALL)
                        .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                        .navigation();
            }
        } else {
            // 创建临时对讲组
            TempChannel tempChannel = ICPRtcManager.getsInstance().createTempAudioPTTChannel(userList);
            ICPRtcManager.getsInstance().joinChannel(tempChannel.getChannelNumber() + "");
            if (homeViewPager != null) {
                homeViewPager.setCurrentItem(0);
            }
        }
        
        adapter.clearSelection();
        // 执行操作后自动关闭弹窗
        if (actionsPopup != null && actionsPopup.isShowing()) {
            actionsPopup.dismiss();
        }
    }
    
    @Override
    public void onVideoCallClicked() {
        Set<User> users = adapter.getSelectedUsers();
        if (users == null || users.isEmpty() || users.size() > 1) {
            return;
        }
        
        List<User> userList = new ArrayList<>(users);
        // 单人视频通话
        if (YLIMConfig.windowManagerChoose) {
//            MeetManger.getInstance().startMeet(
//                    requireContext().getApplicationContext(),
//                    0,
//                    userList.get(0).getNumber() + "",
//                    null,
//                    ICPRtcEventHandler.SessionType.TYPE_VIDEO_CALL,
//                    null,
//                    false);
            ARouter.getInstance()
                    .build(RouterPath.path.av_pop_activity)
                    .withString("callerId", userList.get(0).getNumber() + "")
                    .withInt("type", ICPRtcEventHandler.SessionType.TYPE_VIDEO_CALL)
                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                    .navigation();
        } else {
//            Intent intent = new Intent(requireContext().getApplicationContext(), AvActivity.class);
//            intent.putExtra("callerId", userList.get(0).getNumber() + "");
//            intent.putExtra("type", ICPRtcEventHandler.SessionType.TYPE_VIDEO_CALL);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            requireContext().getApplicationContext().startActivity(intent);

            ARouter.getInstance()
                    .build(RouterPath.path.av_activity)
                    .withString("callerId", userList.get(0).getNumber() + "")
                    .withInt("type", ICPRtcEventHandler.SessionType.TYPE_VIDEO_CALL)
                    .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                    .navigation();
        }
        
        adapter.clearSelection();
        // 执行操作后自动关闭弹窗
        if (actionsPopup != null && actionsPopup.isShowing()) {
            actionsPopup.dismiss();
        }
    }
    
    @Override
    public void onSendMessageClicked() {
        Set<User> users = adapter.getSelectedUsers();
        if (users == null || users.isEmpty()) {
            return;
        }
        
        List<User> userList = new ArrayList<>(users);
        if (userList.size() == 1) {
            // 单人消息
            MessageDialogue md = ICPRtcManager.getsInstance().createMessageDialogueIfNeed(userList.get(0));
            ChatMessageActivity.show(requireActivity(), md.getChat_id());
        } else {
            // 群组消息
            MessageDialogue md = ICPRtcManager.getsInstance().createBroadcastMessageDialogue(userList);
            Log.e(TAG, "onSendMessageClicked: 创建临时对讲组:"+md.getName() + "chatId:"+md.getChat_id());
            ChatMessageActivity.show(requireActivity(), md.getChat_id());
        }
        
        adapter.clearSelection();
        // 执行操作后自动关闭弹窗
        if (actionsPopup != null && actionsPopup.isShowing()) {
            actionsPopup.dismiss();
        }
    }

    @Override
    public void onDestroyView() {
        Log.d(TAG, "onDestroyView: 销毁视图");
        // 清除handler回调，防止内存泄漏
        mainHandler.removeCallbacksAndMessages(null);
        
        // 确保在Fragment销毁时关闭弹窗，避免窗口泄漏
        if (actionsPopup != null && actionsPopup.isShowing()) {
            actionsPopup.dismiss();
        }
        
        super.onDestroyView();
    }

    /**
     * 滚动到指定位置并确保完全可见
     */
    private void scrollToPosition(int position) {
        RecyclerView recyclerView = getMBinding().recyclerView;
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        if (layoutManager != null) {
            // 平滑滚动到指定位置
            layoutManager.smoothScrollToPosition(recyclerView, null, position);
        }
    }

    /**
     * 显示底部联系人操作弹窗
     */
    private void showContactActionsPopup() {
        if (actionsPopup == null) {
            actionsPopup = new ContactActionsPopup(requireContext(), this);
            actionsPopup.setPopupStateListener(this);
        }
        
        // 更新选中联系人数量显示
        Set<User> selectedUsers = adapter.getSelectedUsers();
        actionsPopup.updateSelectedCount(selectedUsers.size());
        
        // 显示弹窗，从底部弹出
        if (!actionsPopup.isShowing()) {
            actionsPopup.show(getMBinding().getRoot());
        }
    }
    
    @Override
    public void onPopupShown(int height) {
        // 弹窗显示时，增加RecyclerView的底部padding，防止内容被遮挡
        RecyclerView recyclerView = getMBinding().recyclerView;
        recyclerView.setPadding(
            recyclerView.getPaddingLeft(),
            recyclerView.getPaddingTop(),
            recyclerView.getPaddingRight(),
            originalPaddingBottom + height
        );
        
        // 如果有选中的最后一个item，确保它可见
        int lastVisiblePosition = getLastVisiblePosition();
        int selectedPosition = adapter.getLastSelectedPosition();
        
        if (selectedPosition != -1 && selectedPosition > lastVisiblePosition - 3) {
            // 滚动到选中的位置，确保完全可见
            scrollToPosition(selectedPosition);
        }
    }
    
    @Override
    public void onPopupDismissed() {
        // 弹窗消失时，恢复RecyclerView的原始底部padding
        RecyclerView recyclerView = getMBinding().recyclerView;
        recyclerView.setPadding(
            recyclerView.getPaddingLeft(),
            recyclerView.getPaddingTop(),
            recyclerView.getPaddingRight(),
            originalPaddingBottom
        );
    }
    
    /**
     * 获取当前可见的最后一个item的位置
     */
    private int getLastVisiblePosition() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) getMBinding().recyclerView.getLayoutManager();
        if (layoutManager != null) {
            return layoutManager.findLastVisibleItemPosition();
        }
        return 0;
    }
}